module DATE where
import Char
import Data.Time.Calendar
import Data.Time.LocalTime
import Locale
import Data.Time.Format
import Data.Time.Clock
import Data.Time.Calendar.WeekDate
import Data.Maybe
import System.Environment
import System.Locale
import System.Time (getClockTime, toCalendarTime, formatCalendarTime)

data  DateTime = DateTime Day TimeOfDay deriving (Eq, Ord) 

instance Show DateTime where 
	show (DateTime a b) = show a ++ " " ++ show b

-- Funckja do wyswietlania dnia
show2 (DateTime a b) = show a

-- Funckja do wyswietlania roku i miesiaca
show3 (DateTime a b) = show ((show y)++"-"++(show m)) where
	(y,m,d) = toGregorian a

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy _ [] = []
splitBy f list = first : splitBy f (dropWhile f rest) where
	(first, rest) = break f list

-- Funkcja parsuje ciag znakow tworzac Date
parseDateTime:: String -> DateTime
parseDateTime s =  DateTime (if ((fromGregorianValid  year month day) /= Nothing) then fromJust (fromGregorianValid  year month day) else error "Niepoprawny format dnia")  ( if (makeTimeOfDayValid hour minute 0 /= Nothing) then fromJust (makeTimeOfDayValid hour minute 0) else error "Niepoprawny format godziny.") 
	where
		year	= parseYear date
		month	= parseMonth date
		day 	= parseDay date
		hour	= parseHour time
		minute	= parseMinute time
		date = head (splitBy (== ' ') s)
		time = last (splitBy (== ' ') s)
		parseYear date = read (head (splitBy (== '-') date)) ::Integer
		parseMonth date = read (last (take 2 (splitBy (== '-') date)) ) ::Int
		parseDay date = read (last ( (splitBy (== '-') date)) ) ::Int
		parseHour time  = read (head (splitBy (== ':') time)) ::Int
		parseMinute time =	read (last (splitBy (== ':') time)) ::Int

-- Funkcja zwraca aktualna date				 
pobierzAktualnaDate = do {
				time <- (getClockTime >>= toCalendarTime);
				return $ formatCalendarTime defaultTimeLocale "%Y-%m-%d %H:%M:00" time;	
			}

-- Funkcja sprawdzajaca poprawnosc formatu wprowadzonej daty
sprawdzDate [] = False
sprawdzDate (x) = if ( (length x) ==16 && (isDigit (x!!0)) && (isDigit (x!!1)) && (isDigit (x!!2)) && (isDigit (x!!3)) && 
													(x!!4)=='-' && (isDigit (x!!5)) && (isDigit (x!!6)) && 
													(x!!7)=='-' && (isDigit (x!!8)) && (isDigit (x!!9)) && 
													(x!!10)==' ' && (isDigit (x!!11)) && (isDigit (x!!12)) && 
													(x!!13)==':' && (isDigit (x!!14)) && (isDigit (x!!15))) then True
					else False
